<template>
  <view>
    <a-modal title="表名" :visible="showTableName" okText="确定" cancelText="取消" @ok="handleCancelTableName"
             @cancel="handleCancelTableName">
      <input @input="e => handleChange(e.target.value, -1, '')"/>
    </a-modal>

    <a-modal :visible="show" :confirm-loading="confirmLoading" okText="确定" cancelText="取消" @ok="createTable"
             @cancel="handleModelCancel">
      <view>
        <a-button v-if="tableName == ''" style="margin-bottom: 10px" @click="handleAdd">
          增加
        </a-button>

        <a-table bordered :data-source="dataSource" :columns="columns" :scroll="{ x: 500 }" :pagination="false">
          <view
              v-for="col in ['fieldName', 'note', 'defaultValue']"
              :slot="col"
              slot-scope="text, record, index"
          >
            <view :key="col">
              <input v-if="record.editable" style="margin: -5px 0"
                     @input="e => handleChange(e.target.value, record.key, col)"/>
              <view v-else>
                {{ text }}
              </view>
            </view>
          </view>

          <view slot="length" slot-scope="text, record, index">
            <view key="length">
              <input type="number" v-if="record.editable" style="margin: -5px 0"
                     @input="e => handleChange(e.target.value, record.key, 'length')"/>
              <view v-else>
                {{ text }}
              </view>
            </view>
          </view>

          <view slot="type" slot-scope="text, record, index">
            <a-select v-if="record.editable" :defaultValue="text" style="width: 125px"
                      @change="handleChange($event, record.key, 'type')">
              <a-select-option :value="item" v-for="(item, index) in type" :key="index">
                {{ item }}
              </a-select-option>
            </a-select>
            <view v-else>
              {{ text }}
            </view>
          </view>

          <view slot="isNull" slot-scope="text, record, index">
            <a-radio-group v-model="record.pk" @change="onChange"
                           :disabled="record.editable !== '' && !record.editable">
              <a-radio :value='false'>
                是
              </a-radio>
              <a-radio :value='true'>
                否
              </a-radio>
            </a-radio-group>
          </view>

          <view slot="pk" slot-scope="text, record, index">
            <a-radio-group v-model="record.pk" @change="onChange"
                           :disabled="record.editable !== '' && !record.editable">
              <a-radio :value='true'>
                是
              </a-radio>
              <a-radio :value='false'>
                否
              </a-radio>
            </a-radio-group>
          </view>

          <view slot="operation" slot-scope="text, record, index">
            <a-popconfirm
                v-if="dataSource.length"
                title="确定删除?"
                @confirm="() => onDelete(record.key)"
                okText="确定"
                cancelText="取消"
            >
              <a href="javascript:;">删除</a>
            </a-popconfirm>

            <a-divider type="vertical"/>

            <span v-if="record.editable">
            <a @click="() => save(record.key)">保存</a>
            <a-popconfirm title="确定取消?" @confirm="() => cancel(record.key)" okText="确定" cancelText="取消">
              <a>取消</a>
            </a-popconfirm>
          </span>
            <span v-else>
            <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
          </span>
          </view>
        </a-table>
      </view>
    </a-modal>

    <iframe id="id_iframe" name="nm_iframe" style="display:none;"></iframe>
  </view>
</template>

<script>
export default {
  name: "tablestructure",
  props: {
    show: Boolean,
    id: Number,
    dbName: String,
    tableName: {
      default: '',
    },
    handleOk: Function,
    handleCancel: Function
  },
  data() {
    return {
      columns: [
        {
          title: '字段名',
          dataIndex: 'fieldName',
          width: '125px',
          scopedSlots: {customRender: 'fieldName'},
        },
        {
          title: '类型',
          dataIndex: 'type',
          width: '150px',
          scopedSlots: {customRender: 'type'},
        },
        {
          title: '长度',
          dataIndex: 'length',
          width: '75px',
          scopedSlots: {customRender: 'length'},
        },
        {
          title: '主键',
          dataIndex: 'pk',
          width: '150px',
          scopedSlots: {customRender: 'pk'},
        },
        {
          title: '是否为空',
          dataIndex: 'isNull',
          width: '150px',
          scopedSlots: {customRender: 'isNull'},
        },
        {
          title: '注释',
          dataIndex: 'note',
          width: '100px',
          scopedSlots: {customRender: 'note'},
        },
        {
          title: '默认值',
          dataIndex: 'defaultValue',
          width: '125px',
          scopedSlots: {customRender: 'defaultValue'},
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '200px',
          scopedSlots: {customRender: 'operation'},
        },
      ],
      confirmLoading: false,
      dataSource: [],
      count: 0,
      editingKey: '',
      type: [
        'bigint',
        'binary',
        'bit',
        'blob',
        'char',
        'date',
        'datetime',
        'decimal',
        'double',
        'enum',
        'float',
        'geometry',
        'geometrycollection',
        'int',
        'integer',
        'json',
        'linestring',
        'longblob',
        'longtext',
        'mediumblob',
        'mediumint',
        'mediumtext',
        'multilinestring',
        'multipoint',
        'multipolygon',
        'numeric',
        'point',
        'polygon',
        'real',
        'set',
        'smallint',
        'text',
        'time',
        'timestamp',
        'tinyblob',
        'tinyint',
        'tinytext',
        'varbinary',
        'varchar',
        'year'
      ],
      showTableName: false
    }
  },
  methods: {
    handleAdd() {
      const {count, dataSource} = this;
      const newData = {
        key: count,
        fieldName: ``,
        type: ``,
        length: ``,
        isNull: false,
        pk: false,
        note: ``,
        defaultValue: ''
      };
      this.dataSource = [...dataSource, newData];
      this.count = count + 1;
      this.cacheData = this.dataSource.map(item => ({...item}))
    },
    createTable() {
      let isExitTableName = this.tableName == ''
      if (isExitTableName) {
        this.showTableName = true
        return
      }

      this.$axios({
        url: '/create/table',
        method: 'post',
        data: {
          id: this.id,
          dbName: this.dbName,
          tableName: this.tableName,
          list: this.dataSource,
        }
      }).then((res) => {
        this.handleModelCancel()
      })
    },
    onDelete(key) {
      const dataSource = [...this.dataSource];
      this.dataSource = dataSource.filter(item => item.key !== key);
      this.cacheData = this.dataSource.map(item => ({...item}))
    },
    onChange() {

    },
    edit(key) {
      const newData = [...this.dataSource];
      const target = newData.filter(item => key === item.key)[0];
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.dataSource = newData;
      }
    },
    handleChange(value, key, column) {
      if (key == -1 && column == '') {
        this.tableName = value
      }
      const newData = [...this.dataSource];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        target[column] = value;
        this.dataSource = newData;
      }
    },
    save(key) {
      const newData = [...this.dataSource];
      const newCacheData = [...this.cacheData];
      const target = newData.filter(item => key === item.key)[0];
      const targetCache = newCacheData.filter(item => key === item.key)[0];
      if (target && targetCache) {
        delete target.editable;
        this.dataSource = newData;
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      this.editingKey = '';
    },
    cancel(key) {
      const newData = [...this.dataSource];
      const target = newData.filter(item => key === item.key)[0];
      this.editingKey = '';
      if (target) {
        Object.assign(target, this.cacheData.filter(item => key === item.key)[0]);
        delete target.editable;
        this.dataSource = newData;
      }
    },
    selectTableStructure() {
      this.$axios({
        url: '/select/table/struct',
        method: 'post',
        data: {
          id: this.id,
          dbName: this.dbName,
          tableName: this.tableName
        }
      }).then((res) => {
        this.dataSource = res.data.data
      })
    },
    handleCancelTableName() {
      this.showTableName = false;
    },
    handleModelCancel() {
      this.dataSource = []
      this.handleCancel()
    }
  },
  created() {
    if (this.tableName != '') {
      this.selectTableStructure()
    }
  }
}
</script>

<style>
input {
  border: 1px solid #ddd
}
</style>
